package com.taobao.snowsnow.taobao;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.sql.Timestamp;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.tree.DefaultElement;

import com.taobao.api.*;
import com.taobao.api.request.*;
import com.taobao.api.response.ItemGetResponse;
import com.taobao.api.response.ItemsOnsaleGetResponse;
import com.taobao.snowsnow.hibernate.pojo.Color;
import com.taobao.snowsnow.hibernate.pojo.Dimension;
import com.taobao.snowsnow.hibernate.pojo.ProductCollect;
import com.taobao.snowsnow.hibernate.service.ColorService;
import com.taobao.snowsnow.hibernate.service.DimensionService;
import com.taobao.snowsnow.hibernate.service.ItemCollectService;
import com.taobao.snowsnow.util.ApplicationContextUtil;
import com.taobao.snowsnow.util.GB2Alpha;

public class ProductSync extends Taobao {

	private ProductCollect productCollect = null;
	private ItemCollectService itemService;
	private ColorService colorService;
	private DimensionService dimensionService;
	int jj = 0;
	private StringBuffer buffer = new StringBuffer();
	
	int i = 0;
	
	private void initService() {
		itemService = (ItemCollectService) ApplicationContextUtil.getBean("ItemCollectService");
		colorService = (ColorService) ApplicationContextUtil.getBean("ColorService");
		dimensionService = (DimensionService) ApplicationContextUtil.getBean("DimensionService");
	}
	
	public ProductSync() throws Exception {
		initService();
		getPage();
	}
	
	public ProductSync(boolean single) throws ApiException, DocumentException {
		initService();
	}
	
	/**
	 * 获取一个分页的商品
	 * @throws Exception 
	 */
	private void getPage() throws Exception {
		ItemsOnsaleGetRequest req = new ItemsOnsaleGetRequest();
		
//			ItemsGetRequest req = new ItemsGetRequest();

		// 获取 num_iid, 用来获取商品详情
		req.setFields("num_iid");

		// 淘宝id名称
//			req.setNicks("myleft1");

		// 每页大小
		req.setPageSize(40l);
		
		for(long i = 1; i <= 40l; i++) {
			// 页码
			req.setPageNo(i);
			
			// sessionKey
			ItemsOnsaleGetResponse response = client.execute(req, TaoBaoUtil.SESSIONKEY);

			getItems(response.getBody());
		}
		
		System.out.println("over");
		output(buffer.toString());
			
	}

	/**
	 * 获取多个商品
	 * @param xmlBody
	 * @throws Exception 
	 */
	@SuppressWarnings("unchecked")
	public void getItems(String xmlBody) throws Exception {
		Document document = DocumentHelper.parseText(xmlBody);

		List<DefaultElement> list = document.selectNodes("//items_onsale_get_response/items/item");
		
		for (DefaultElement df : list) {
			
			Element num_iid = df.element("num_iid");
			
			long iid = Long.valueOf(num_iid.getText());
//					System.out.println(iid);

			ItemGetRequest req1 = new ItemGetRequest();
			req1.setFields("num_iid, created, title, detail_url, pic_url, property_alias, sku");
			req1.setNumIid(iid);

			ItemGetResponse response = client.execute(req1, TaoBaoUtil.SESSIONKEY);
			getItem(response.getBody());
//			System.out.println(i++);
		}
	}
	
	/**
	 * 获取单个商品
	 * @param xmlBody
	 * @throws Exception 
	 */
	@SuppressWarnings("unchecked")
	private void getItem(String xmlBody) throws Exception {
		Document doc = DocumentHelper.parseText(xmlBody);
		List<DefaultElement> l = doc.selectNodes("//item_get_response/item");
		
		productCollect = new ProductCollect();
		
		for (DefaultElement d : l) {
			
			long num_iid = Long.valueOf(d.element("num_iid").getText());
			
//			System.out.println(num_iid);
			String title = d.element("title").getText();
			// Item的发布时间
			String created = d.element("created").getText();
			String detail_url = d.element("detail_url").getText();
			String pic_url = d.element("pic_url").getText();
			String alias = d.element("property_alias").getText();
			
			productCollect.setNumIid(num_iid);
			productCollect.setName(title);
			productCollect.setItemUrl(detail_url);
			productCollect.setPicUrl(pic_url);
			productCollect.setCreatedTime(Timestamp.valueOf(created));
			productCollect.setPinyin(GB2Alpha.String2Alpha(title));
			
			List<DefaultElement> sku = doc.selectNodes("//skus/sku");
			
			String[] split = alias.split(";");
			
			getSku(sku, split);
			itemService.create(productCollect);
		}
	}
	
	/**
	 * 根据给定的numiid来创建商品
	 * @param numiid
	 * 			淘宝的商品iid
	 * @throws Exception 
	 */
	@SuppressWarnings("unchecked")
	public void createItem(long numiid) throws Exception {
		ItemGetRequest req = new ItemGetRequest();
		req.setFields("num_iid, created, title, detail_url, pic_url, property_alias, sku");
		req.setNumIid(numiid);

		ItemGetResponse response = client.execute(req, TaoBaoUtil.SESSIONKEY);
		
		Document doc = DocumentHelper.parseText(response.getBody());
		List<DefaultElement> l = doc.selectNodes("//item_get_response/item");
		
		productCollect = new ProductCollect();
		
		for (DefaultElement d : l) {
			
			long num_iid = Long.valueOf(d.element("num_iid").getText());
			
//			System.out.println(num_iid);
			String title = d.element("title").getText();
			// Item的发布时间
			String created = d.element("created").getText();
			String detail_url = d.element("detail_url").getText();
			String pic_url = d.element("pic_url").getText();
			String alias = d.element("property_alias").getText();
			
			productCollect.setNumIid(num_iid);
			productCollect.setName(title);
			productCollect.setItemUrl(detail_url);
			productCollect.setPicUrl(pic_url);
			productCollect.setCreatedTime(Timestamp.valueOf(created));
			productCollect.setPinyin(GB2Alpha.String2Alpha(title));
			
			
			List<DefaultElement> sku = doc.selectNodes("//skus/sku");
			
			String[] split = alias.split(";");
			
//			ps.update(product);
//			product.setHref(detail_url);
//			product.setPic(new Pic(title, pic_url));
//			product.setCreated(Util.getDate(created));
			
			getSku(sku, split);
			itemService.create(productCollect);
		}
//			ps.saveOrUpdate(product);
	}


	/**
	 * @param mw
	 * @param sku
	 * @param split
	 * @return
	 */
	private void getSku(List<DefaultElement> sku, String[] split) {
		for(DefaultElement s : sku) {
			String properties = s.element("properties").getText();
//			String quantity = s.element("quantity").getText();
//			String price = s.element("price").getText();
			
			for(String tmp : split) {
				if(tmp.contains(properties)) {
					// 创建单个商品
					create(tmp);
					buffer.append(tmp + "\n");
//					System.out.println(tmp);
				}
			}
		}
	}
	
	private void create(String tmp) {
		SkuParse sku = new SkuParse(tmp);
		Color color = null;
		Dimension dimension = null;
		
		if(sku.getColor() != null) {
			color = colorService.findByNamePrecise(sku.getColor());
			
			if(color == null)
				color = new Color(sku.getColor(), "", "", "");
			
			if(!productCollect.getColors().contains(color))
				productCollect.getColors().add(color);
		}
		
		if(sku.getSpecs() != null) {
			dimension = dimensionService.findByNamePrecise(sku.getSpecs());
			
			if(dimension == null)
				dimension = new Dimension(sku.getSpecs(), "");
			
			if(!productCollect.getDimensions().contains(dimension)) 
				productCollect.getDimensions().add(dimension);
		}
	}

	private void output(String str) {
	    FileOutputStream fos;
		try {
			fos = new FileOutputStream("d:/sku.txt");
			Writer out = new OutputStreamWriter(fos, "utf-8");  
		    out.write(str);  
		    out.close();  
		    fos.close();  
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}  
	}
	
	public static void main(String[] args) {
		try {
			new ProductSync();
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
